﻿/**
 * 
 * Copyright 2009, 2010 Mike Jamer [email: mikejamer@gmail.com ]
 * 
 * This File is part of Moose IRC
 * 
 * MooseIRC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * MooseIRC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MooseIRC.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

using System;
using System.Net;
using System.Net.Sockets;
using moose.irc.extension;

namespace moose.irc.actions.commands {
    /// <summary>
    /// Command enables Session to connect to IRC Server
    /// </summary>
    /// <remarks>
    /// There's alot of work to do here, 
    /// and i'm not sure where to start tackling it.  I want to have
    /// configurable server lists, and rather than hand in a host and a port (though you could),
    /// you would instead ask it to connect to say.. undernet.  And it would try to 
    /// connect to every server in undernet, if connections fail.
    /// 
    /// this will likely be implented as an extension action...
    /// </remarks>
    [CLSCompliant(true)]
    [Action(Type = ActionTypes.Command, 
        Name = "moose-std-cmd-connect", 
        Description = "Connects Session to IRC Server", 
        Version = "0.1", 
        Author = "Mike MacKenzie-Jamer<email:mikejamer@gmail.com")]
    [Trigger(TriggerText = "server")]
    public sealed class ConnectCommand : IrcAction {

        /// <summary>
        /// Returns States, Valid for this command to execute 
        /// </summary>
        /// <returns>
        /// A <see cref="IrcSessionStates"/>
        /// </returns>
        public override IrcSessionStates valid_states() {
            return IrcSessionStates.Disconnected | IrcSessionStates.None;
        }

        /// <summary>
        /// Connect to IRC Server 
        /// </summary>
        public override void action(IrcSession session, IrcMessage message) {
            if (!validate_input(session, message)) return;
            connect(session, message); return;
        }

        /// <summary>
        /// Validates the input for this command 
        /// </summary>
        /// <param name="message">
        /// A <see cref="IrcMessage"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.Boolean"/>
        /// </returns>
        private bool validate_input(IrcSession session, IrcMessage message) {
            bool valid = true;
            int port;
            if (message.Arguments.Length != 2) {
                session.notify_event(IrcEvent.createEchoEvent("-:Connect:- Must Provide two arguments, host [and] port"));
                valid = false;
            } else { //Must have two arguments for these validations to properly fire...
                if (!int.TryParse(message.Arguments[1], out port)) {
                    session.notify_event(IrcEvent.createEchoEvent("-:Connect:- Port must be numeric"));
                    valid = false;
                }
                if (port < 1 || port > 65535) {
                    session.notify_event(IrcEvent.createEchoEvent("-:Connect:- port must be between 1 and 65535"));
                    valid = false;
                }
            }

            return valid;
        }

        /// <summary>
        /// Attempt to resolve the host string
        /// </summary>
        /// <param name="host">
        /// A <see cref="System.String"/>
        /// </param>
        /// <returns>
        /// A <see cref="EndPoint"/>
        /// </returns>
        private IPHostEntry resolve(string host) {
            return Dns.GetHostEntry(host);
        }

        /// <summary>
        /// Connect to IRC Server
        /// </summary>
        private void connect(IrcSession session, IrcMessage message) {
            session.notify_event(IrcEvent.createEchoEvent("-:Connect:- Connecting to " + message.Arguments[0] + " : " + message.Arguments[1]));
            IPHostEntry entry = resolve(message.Arguments[0]);
            int port = int.Parse(message.Arguments[1]); //We've already validated that this will parse, so this should be safe
            IPEndPoint remote_endpoint;
            foreach (IPAddress address in entry.AddressList) {
                session.notify_event(IrcEvent.createEchoEvent("-:Connect:- Connecting To: " + address.ToString()));
                remote_endpoint = new IPEndPoint(address, port);
                session.Connection.connect(remote_endpoint);

                if (session.Connection.Connected) {
                    //Notify client that we have connected
                    session.notify_event(new IrcEvent(IrcEventTypes.ServerConnected));
                    break;
                }
            }

            if (session.Connection.Connected) {
                session.SessionState = IrcSessionStates.Connected;
                session.notify_event(IrcEvent.createEchoEvent("-:Connect:- Connected to: " + message.Arguments[0]));
                session.notify_event(new IrcEvent(IrcEventTypes.ServerConnected));
            } else {
                session.SessionState = IrcSessionStates.Disconnected;
                session.notify_event(IrcEvent.createEchoEvent("-:Connect:- Failed to Connected to: " + message.Arguments[0]));
                session.notify_event(new IrcEvent(IrcEventTypes.ServerDisconnected));
            }

            return;
        }

    }
}
